package com.example.tests;

import com.example.framework.ContactData;
import com.example.utils.SortedListOf;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import static org.testng.AssertJUnit.assertTrue;

public class ContactSearchTest extends TestManager{
    Random rnd = new Random();

    @DataProvider
    public Iterator<Object[]> searchString(){
        List<Object[]> list = new ArrayList<Object[]>();

        for (int i = 0; i < 1; i++) {
            String searchString = dataGen.getRandomAlphanumericString(1);
            list.add(new Object[]{searchString});
        }
        return list.iterator();
    }

    @Test(dataProvider = "searchString")
    public void shouldSearchContact(String searchString){
        manager.getContactHelper().searchContact(searchString);

        // save new state
        SortedListOf<ContactData> newContactList = manager.getContactHelper().getFoundContacts();

        assertTrue(isSearchCorrect(newContactList, searchString));

    }

    private boolean isSearchCorrect(SortedListOf<ContactData> newContactList, String searchedString) {
        for(ContactData contact: newContactList){
            if (!isContactContainsSearchedString(contact, searchedString)) return false;
        } return true;
    }

    private boolean isContactContainsSearchedString(ContactData contact, String searchedString){
        if (contact.getFirstName().contains(searchedString) ||
            contact.getLastName().contains(searchedString) ||
            contact.getEmail().contains(searchedString)){
            return true;
        }
        return false;
    }
}
